package com.hengxinguotong.zhihuichengjian.utils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.JumpBean;
import com.hengxinguotong.zhihuichengjian.ui.LoginActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;

/**
 * 工具集
 */
public class Utils
{
    /**
     * 服务端的访问的根目录
     */
//    private static String SERVER_URL = "http://192.168.10.117:8081/";//戴文杰
//    private static String SERVER_URL = "http://192.168.10.194:8080";//金诚测试环境
//    private static String SERVER_URL = "http://192.168.10.178:8080/escst_interface";//聂晶本地
//    private static String SERVER_URL = "http://10.40.55.66:8089/escst_interface/";//测试环境
//    private static String SERVER_URL = "http://221.234.44.78:81/escst_interface/";//正式环境
//    private static String SERVER_URL = "http://58.49.51.35:8899/escst_interface/";//正式环境11.25
//    private static String SERVER_URL = "http://42.51.69.36:8080/escst_interface/";//正式环境12.02
    private static String SERVER_URL = "http://223.75.250.147:10081/escst_interface/";//正式环境12.12

//    private static String SERVER_URL = "http://192.168.10.97:80/escst_interface/";//测试环境
//    private static String SERVER_URL = "http://10.10.10.11:8088/escst_interface";//测试环境
//    private static String SERVER_URL = "http://221.234.44.78:8069/escst_interface/";//正式环境
//    private static String SERVER_URL = "http://192.168.1.114:8084/escst_interface_war_exploded/";//胡斐测试环境


    public static void setServerUrl(Activity activity, String serverUrl)
    {
        SERVER_URL = serverUrl;
        SPUtil.put(activity, "SERVER_URL", SERVER_URL);
    }

    public static String getServerUrl(Activity activity)
    {
        if (!isEmpty(SPUtil.getString(activity, "SERVER_URL")))
        {
            return SPUtil.getString(activity, "SERVER_URL");
        } else
        {
            return SERVER_URL;
        }
    }

    private static final String PHONE_PATTERN = "[1]{1}[3,4,5,8,7]{1}[0-9]{9}";
    private static final String VALID_STRING = "^[A-Za-z0-9\\u4e00-\\u9fa5]+$";
    private static final String TAG = "Utils";
    private static Typeface typeFace;
    public static final int ONCECOUNT = 10;
    public static final String ADDPIC = "addpic";


    public static Typeface getTypeface(Context context)
    {
        if (typeFace == null)
        {
            typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/sysz.ttf");
        }
        return typeFace;
    }

    /**
     * @param character
     * @return
     * @Title : filter
     * @Type : FilterStr
     * @Description : 过滤出字母、数字和中文
     */
    public static boolean isValidString(String character)
    {
        if (TextUtils.isEmpty(character))
            return false;
        return character.matches(VALID_STRING);
    }


    private static ProgressDialog pBar;

    public static String getWeekDay(String pTime)
    {

        String Week = "";


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try
        {

            c.setTime(format.parse(pTime));

        } catch (ParseException e)
        {
            e.printStackTrace();
        }

        switch (c.get(Calendar.DAY_OF_WEEK))
        {
            case Calendar.SUNDAY:
                Week += "天";
                break;
            case Calendar.MONDAY:
                Week += "一";
                break;
            case Calendar.TUESDAY:
                Week += "二";
                break;
            case Calendar.WEDNESDAY:
                Week += "三";
                break;
            case Calendar.THURSDAY:
                Week += "四";
                break;
            case Calendar.FRIDAY:
                Week += "五";
                break;
            case Calendar.SATURDAY:
                Week += "六";
                break;
        }

        return Week;
    }

    public static String geNowTime()
    {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formate = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm");
        return formate.format(date);
    }

    public static String geCurrentTime()
    {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formate = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm");
        return formate.format(date);
    }

    //判断应用是否拥有某种权限
    public static boolean hasPermission(Context context, String permission)
    {
        int perm = context.checkCallingOrSelfPermission(permission);
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    public static boolean isEmpty(String str)
    {
        if (str == null)
        {
            return true;
        }


        if ("".equals(str))
        {
            return true;
        }


        if ("".equals("null"))
        {
            return true;
        }

        return false;

    }


    public static String getWeek() throws ParseException
    {
        String week;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
        Calendar cal = Calendar.getInstance();
        Date date = new Date(System.currentTimeMillis());
        cal.setTime(date);
        //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
        if (1 == dayWeek)
        {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);//根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        week = sdf.format(cal.getTime()) + "#";
        cal.add(Calendar.DATE, 6);
        week = week + sdf.format(cal.getTime());
        return week;

    }

    public static String geTime()
    {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formate = new SimpleDateFormat(
                "yyyy-MM-dd");
        return formate.format(date);
    }

    //判断昨天
    public static Date getNextDay(Date date)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        return date;
    }

    public static String geDate()
    {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat formate = new SimpleDateFormat(
                "yyyy年MM月dd号");
        return formate.format(date);
    }

    public static int getYear(String time)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int year = 0;
        try
        {
            Date date = sdf.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            year = calendar.get(Calendar.YEAR);
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        return year;
    }

    public static String getMonthAndDay(String time)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int month = 0,
                day = 0;
        try
        {
            Date date = sdf.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            month = calendar.get(Calendar.MONTH) + 1;
            day = calendar.get(Calendar.DAY_OF_MONTH);
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        String m, d;
        if (month < 10)
        {
            m = "0" + month;
        } else
        {
            m = month + "";
        }

        if (day < 10)
        {
            d = "0" + day;
        } else
        {
            d = day + "";
        }

        return m + "-" + d;
    }

    public static boolean judgeNetConnected(Context context)
    {
        // 获取连接管理者
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 获取可用的网络信息
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null)
        {
            return false;
        }
        // 获取网络类型
        int type = networkInfo.getType();
        switch (type)
        {
            // 判断网络类型如果是流量或是wifi,则证明有网
            case ConnectivityManager.TYPE_MOBILE:
            case ConnectivityManager.TYPE_WIFI:
                return true;

            default:
                return false;
        }
    }


    /**
     * 自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    public static Dialog createLoadingDialog(Context context, String msg)
    {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局

        // main.xml中的ImageView
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.iv_loading);
        TextView tipTextView = (TextView) v.findViewById(R.id.tv_tip);
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                context, R.anim.loading_animation);
        // 使用ImageView显示动画
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        if (msg != null)
        {
            tipTextView.setText(msg);// 设置加载信息
        }
        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setCancelable(true);// 可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        return loadingDialog;

    }


    //联网加载数据

    public interface ListenerJson
    {
        public void onSuccess(String json);

        public void onFailure(String json);
    }

    //加载数据
    public static void requestData(final String marked, final Activity activity, String url, RequestParams params, final ListenerJson listenerJson)
    {

        if (!judgeNetConnected(activity))
        {
            Toast.makeText(activity, "网络连接异常!", Toast.LENGTH_LONG).show();
            return;
        }

        String appVersion = getVersionName(activity);
        if (null == params)
        {
            params = new RequestParams();
        }
        params.addHeader("appVersion", appVersion);

        HttpUtils httpUtils = new HttpUtils();
        httpUtils.configCurrentHttpCacheExpiry(1000 * 30);// 请求结果缓存时间
        if (marked != null)
        {
            startDownload(marked, activity);
        }
        Log.i(TAG, "Activity："+activity.getLocalClassName()+"\nURL：" + getServerUrl(activity) + url);
        try
        {
            httpUtils.send(HttpRequest.HttpMethod.POST, getServerUrl(activity) + url, params,
                    new RequestCallBack<String>()
                    {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo)
                        {

                            if (marked != null)
                            {
                                stopDownLoad();
                            }
                            Logger.d("responseInfo.result----" + responseInfo.result);
                            //activity 销毁后不再返回数据
                            if (!ActivityController.activities.contains(activity))
                            {
                                return;
                            }
                            try
                            {
                                JSONObject object = new JSONObject(responseInfo.result);
                                String status = object.getString("status");
                                String msg = object.getString("msg");
                                if ("-1".equals(status))
                                {
                                    Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
                                    loginOut(activity);
                                    return;
                                } else if ("0".equals(status))
                                {
                                    listenerJson.onFailure(responseInfo.result);
                                } else
                                {
                                    listenerJson.onSuccess(responseInfo.result);
                                }
                            } catch (JSONException e)
                            {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onFailure(HttpException e, String s)
                        {
                            if (marked != null)
                            {
                                stopDownLoad();
                            }
                            listenerJson.onFailure(s);
                            Log.d(TAG, e.toString()+ "\n" +e.getExceptionCode()+ "\n" + s);
                            if (e.getExceptionCode() == 0 && s.equals("java.net.SocketTimeoutException"))
                            {
                                Toast.makeText(activity, "网络超时，请稍后重试！", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        } catch (Exception e)
        {
            if (marked != null)
            {
                stopDownLoad();
            }
            Toast.makeText(activity, "提交失败！", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            listenerJson.onFailure("");
        }
    }

    //加载数据
    public static void requestData(final Activity activity, String url, RequestParams params, final ListenerJson listenerJson)
    {

        if (!judgeNetConnected(activity))
        {
            Toast.makeText(activity, "网络连接异常!", Toast.LENGTH_LONG).show();
            return;
        }

        if (null == params)
        {
            params = new RequestParams();
        }
        params.addHeader("appVersion", getVersionName(activity));

        HttpUtils httpUtils = new HttpUtils();
        httpUtils.configCurrentHttpCacheExpiry(1000 * 30);// 设置超时时间

        Log.i(TAG, "Activity："+activity.getLocalClassName()+"\nURL：" + getServerUrl(activity) + url);
        try
        {
            httpUtils.send(HttpRequest.HttpMethod.POST, getServerUrl(activity) + url, params,
                    new RequestCallBack<String>()
                    {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo)
                        {
                            Logger.d("responseInfo.result----" + responseInfo.result);
                            //activity 销毁后不再返回数据
                            if (!ActivityController.activities.contains(activity))
                            {
                                return;
                            }
                            try
                            {
                                JSONObject object = new JSONObject(responseInfo.result);
                                String status = object.getString("status");
                                String msg = object.getString("msg");
                                if ("-1".equals(status))
                                {
                                    Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
                                    loginOut(activity);
                                    return;
                                } else if ("0".equals(status))
                                {
                                    listenerJson.onFailure(responseInfo.result);
                                } else
                                {
                                    listenerJson.onSuccess(responseInfo.result);
                                }
                            } catch (JSONException e)
                            {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onFailure(HttpException e, String s)
                        {
                            listenerJson.onFailure(s);
                            Log.e(TAG, e.toString()+ "\nExceptionCode：" +e.getExceptionCode()+
                                    "\nMessage：" +e.getMessage()+
                                    "\n" + s);
                            if (e.getExceptionCode() == 0 && s.equals("java.net.SocketTimeoutException"))
                            {
                                Toast.makeText(activity, "网络超时，请稍后重试！", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        } catch (Exception e)
        {
            Toast.makeText(activity, "提交失败！", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            listenerJson.onFailure("");
        }
    }

    static Dialog progressDialog;

    public static void startDownload(String marked, Context context)
    {
        if (progressDialog == null)
        {
            progressDialog = Utils.createLoadingDialog(context, marked);
            progressDialog.show();
        } else
        {
            if (!progressDialog.isShowing())
            {
                stopDownLoad();
                startDownload(marked, context);
            }
        }
    }


    public static void stopDownLoad()
    {
        if (progressDialog != null)
        {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }


    public static int getWindowWidth(Activity activity)
    {
        if (activity != null)
        {
            Display display = activity.getWindowManager().getDefaultDisplay();
            DisplayMetrics dm = new DisplayMetrics();
            display.getMetrics(dm);
            return dm.widthPixels;
        } else
        {
            return 0;
        }
    }

    public static int getWindowHeight(Activity activity)
    {
        if (activity != null)
        {
            Display display = activity.getWindowManager().getDefaultDisplay();
            DisplayMetrics dm = new DisplayMetrics();
            display.getMetrics(dm);
            return dm.heightPixels;
        } else
        {
            return 0;
        }
    }


    public static int dip2px(Context context, float dipValue)
    {
        float scale = 0;
        try
        {
            scale = context.getResources().getDisplayMetrics().density;//获取屏幕密度
        } catch (Exception e)
        {

        }
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 调用拨号界面
     *
     * @param phone 电话号码
     */
    public static void call(String phone, Activity activity)
    {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }


    public static boolean isValidPhone(String phone)
    {
        if (TextUtils.isEmpty(phone))
            return false;
        return phone.matches(PHONE_PATTERN);
    }


    public static void disableRadioGroup(RadioGroup testRadioGroup)
    {
        for (int i = 0; i < testRadioGroup.getChildCount(); i++)
        {
            testRadioGroup.getChildAt(i).setEnabled(false);
        }
    }

    public static String getMinPicture(String path)
    {
        String header = path.substring(0, path.lastIndexOf("."));
        String end = path.substring(path.lastIndexOf("."), path.length());
        return header + "_100x100" + end;
    }

    public static void setEditTextViewUnable(String content, EditText editText)
    {
        editText.setEnabled(false);
        if (isEmpty(content))
        {
            editText.setText(" ");
        } else
        {
            editText.setText(content);
        }
    }


    public static void setEditTextViewUnable(String content, TextView textView)
    {
        textView.setClickable(false);
        if (isEmpty(content))
        {
            textView.setText(" ");
        } else
        {
            textView.setText(content);
        }
    }

    /**
     * 设置文本编辑框 如果为空消除hint的文字
     *
     * @param content
     * @param editText
     */
    public static void setEditTextViewHint(String content, EditText editText)
    {
        if (isEmpty(content))
        {
            editText.setText(" ");
        } else
        {
            editText.setText(content);
        }
    }


    public static Bitmap createQRcodeImage(String text)
    {
        try
        {
            if (Utils.isEmpty(text))
            {
                return null;
            }
            int QR_WIDTH = 200;
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE,
                    QR_WIDTH, QR_WIDTH);

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_WIDTH, hints);
            int[] pixels = new int[QR_WIDTH * QR_WIDTH];
            for (int y = 0; y < QR_WIDTH; y++)
            {
                for (int x = 0; x < QR_WIDTH; x++)
                {
                    if (bitMatrix.get(x, y))
                    {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else
                    {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_WIDTH,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_WIDTH);
            return bitmap;
        } catch (WriterException e)
        {
            e.printStackTrace();
            return null;
        }
    }


    public static int getIconByUrl(int url)
    {
        JumpBean jumpBean = Constants.indexHashMap.get(url);
        if (jumpBean != null)
        {
            return jumpBean.getIcon();
        } else
        {
            return 0;
        }
    }

    public static int getSmallIconByUrl(int url)
    {
        JumpBean jumpBean = Constants.indexHashMap.get(url);
        if (jumpBean != null)
        {
            return jumpBean.getSmallIcon();
        } else
        {
            return 0;
        }
    }


    public static void loginOut(Activity activity)
    {
        SPUtil.put(activity, "uuid", "");
        SPUtil.put(activity, "json", "");
        SPUtil.put(activity, "areaId", "");
        SPUtil.put(activity, "level", "");
        SPUtil.put(activity, "userId", "");
        SPUtil.put(activity, "workType", "");
        SPUtil.put(activity, "orgid", "");
        SPUtil.put(activity, SPUtil.getString(activity, "constructionid"), "");//删除工地平面图
        SPUtil.put(activity, "constructionid", "");
        SPUtil.put(activity, "levelName", "");
        SPUtil.put(activity, "realName", "");
        SPUtil.put(activity, "authority", "");
        SPUtil.put(activity, "homeinfo", "");
        SPUtil.put(activity, Constants.MEETING_INFO, "");
//        SPUtil.put(activity, "videoRes", "");
//        Intent intent = new Intent(activity, FloatWindowService.class);
//        activity.stopService(intent);
        Intent intent = new Intent();
        intent.setClass(activity, LoginActivity.class);
//        Toast.makeText(activity, "退出登录", Toast.LENGTH_LONG).show();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); // 注意本行的FLAG设置
        intent.putExtra("logout", "logout");
        activity.startActivity(intent);
        ActivityController.finishAll();
//        activity.finish();
    }

    // 以下是获得版本信息的工具方法

    //版本名
    public static String getVersionName(Context context)
    {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context)
    {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context)
    {
        PackageInfo pi = null;

        try
        {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return pi;
    }

//    public static void downFile(final String url, final Context context)
//    {
//        pBar = new ProgressDialog(context);
//        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        pBar.setTitle("正在下载");
//        pBar.setMessage("请稍候...");
//        pBar.setCancelable(false);//不 可以用“返回键”取消
//        pBar.setProgress(0);
//        pBar.show();
//        new Thread() {
//            public void run() {
//                HttpClient client = new DefaultHttpClient();
//                HttpGet get = new HttpGet(url);
//                HttpResponse response;
//                try {
//                    response = client.execute(get);
//                    HttpEntity entity = response.getEntity();
//                    int length = (int) entity.getContentLength();   //获取文件大小
//                    pBar.setMax(length);                            //设置进度条的总长度
//                    InputStream is = entity.getContent();
//                    FileOutputStream fileOutputStream = null;
//                    //                    URL file_url = new URL(url);
////                    HttpURLConnection conn = (HttpURLConnection)file_url.openConnection();
////                    conn.connect();
////                    int length = (int) conn.getContentLength();   //获取文件大小
////                    pBar.setMax(length);                            //设置进度条的总长度
////                    InputStream is = conn.getInputStream();
//                    if (is != null) {
//                        File file = new File(
//                                Environment.getExternalStorageDirectory(),
//                                "zhcj.apk");
//                        if(file.exists()){
//                            file.delete();
//                        }
//                        file.createNewFile();
//                        fileOutputStream = new FileOutputStream(file);
//                        //这个是缓冲区，即一次读取10个比特，我弄的小了点，因为在本地，所以数值太大一下就下载完了,
//                        //看不出progressbar的效果。
//                        byte[] buf = new byte[1024];
//                        int ch = -1;
//                        int process = 0;
//                        while ((ch = is.read(buf)) != -1) {
//                            fileOutputStream.write(buf, 0, ch);
//                            process += ch;
//                            pBar.setProgress(process);       //这里就是关键的实时更新进度了！
//                        }
//
//                    }
//                    fileOutputStream.flush();
//                    if (fileOutputStream != null) {
//                        fileOutputStream.close();
//                    }
//                    down(context);
//                } catch (ClientProtocolException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//
//        }.start();
//    }

//    private static void down(final Context context)
//    {
//        Looper.prepare();
//        new Handler().post(new Runnable()
//        {
//            public void run()
//            {
//                pBar.cancel();
//                update(context);
//            }
//        });
//        Looper.loop();
//    }

//    private static void update(Context context)
//    {
//
//        Intent install = new Intent();
//        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        install.setAction(android.content.Intent.ACTION_VIEW);
//        install.setDataAndType(Uri.fromFile(new File(Environment
//                        .getExternalStorageDirectory(), "zhcj.apk")),
//                "application/vnd.android.package-archive");
//
//        context.startActivity(install);
//    }

    public static boolean isDebugVersion(Context context)
    {
        try
        {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

}
